import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, DatePicker, Select, Space, Tag, Descriptions, Modal, message } from 'antd';
import { SearchOutlined, ReloadOutlined, EyeOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { RangePicker } = DatePicker;
const { Option } = Select;

// 获取交易记录列表
const fetchTransactions = async (params) => {
  return request('/api/v1/payment/transaction', {
    method: 'GET',
    params,
  });
};

// 获取交易详情
const fetchTransactionDetail = async (id) => {
  return request(`/api/v1/payment/transaction/${id}`, {
    method: 'GET',
  });
};

const TransactionList = () => {
  const [transactions, setTransactions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  const [searchParams, setSearchParams] = useState({});
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentTransaction, setCurrentTransaction] = useState(null);

  // 获取交易记录列表
  const fetchTransactionList = async () => {
    try {
      setLoading(true);
      const res = await fetchTransactions({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      });
      if (res.success) {
        setTransactions(res.data || []);
      } else {
        message.error(res.message || '获取交易记录失败');
      }
    } catch (error) {
      console.error('获取交易记录出错:', error);
      message.error('获取交易记录失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTransactionList();
  }, [pagination.current, pagination.pageSize, searchParams]);

  // 查看交易详情
  const handleViewDetail = async (record) => {
    try {
      setLoading(true);
      const res = await fetchTransactionDetail(record.id);
      if (res.success) {
        setCurrentTransaction(res.data);
        setDetailVisible(true);
      } else {
        message.error(res.message || '获取交易详情失败');
      }
    } catch (error) {
      console.error('获取交易详情出错:', error);
      message.error('获取交易详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '交易单号',
      dataIndex: 'transactionNo',
      key: 'transactionNo',
      width: 180,
    },
    {
      title: '订单号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      width: 180,
    },
    {
      title: '用户',
      dataIndex: 'username',
      key: 'username',
      width: 120,
    },
    {
      title: '交易金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: (text) => `¥${text.toFixed(2)}`,
    },
    {
      title: '支付渠道',
      dataIndex: 'channelName',
      key: 'channelName',
      width: 120,
    },
    {
      title: '交易类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (text) => {
        const typeMap = {
          'payment': '支付',
          'refund': '退款',
          'recharge': '充值',
          'withdraw': '提现',
        };
        return typeMap[text] || text;
      },
    },
    {
      title: '交易状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status) => {
        let color = '';
        let text = '';
        switch (status) {
          case 'success':
            color = 'green';
            text = '成功';
            break;
          case 'pending':
            color = 'gold';
            text = '处理中';
            break;
          case 'failed':
            color = 'red';
            text = '失败';
            break;
          default:
            color = 'default';
            text = status;
        }
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '交易时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button 
          type="primary" 
          icon={<EyeOutlined />} 
          size="small"
          onClick={() => handleViewDetail(record)}
        >
          详情
        </Button>
      ),
    },
  ];

  // 处理搜索
  const handleSearch = (values) => {
    const params = {};
    if (values.transactionNo) {
      params.transactionNo = values.transactionNo;
    }
    if (values.orderNo) {
      params.orderNo = values.orderNo;
    }
    if (values.username) {
      params.username = values.username;
    }
    if (values.type) {
      params.type = values.type;
    }
    if (values.status) {
      params.status = values.status;
    }
    if (values.channelId) {
      params.channelId = values.channelId;
    }
    if (values.dateRange && values.dateRange.length === 2) {
      params.startTime = values.dateRange[0].format('YYYY-MM-DD HH:mm:ss');
      params.endTime = values.dateRange[1].format('YYYY-MM-DD HH:mm:ss');
    }
    
    setSearchParams(params);
    setPagination({
      ...pagination,
      current: 1, // 重置到第一页
    });
  };

  // 重置搜索
  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 处理表格变化
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination(pagination);
  };

  return (
    <PageContainer>
      <Card>
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 24 }}
        >
          <Form.Item name="transactionNo" label="交易单号">
            <Input placeholder="请输入交易单号" allowClear />
          </Form.Item>
          <Form.Item name="orderNo" label="订单号">
            <Input placeholder="请输入订单号" allowClear />
          </Form.Item>
          <Form.Item name="username" label="用户名">
            <Input placeholder="请输入用户名" allowClear />
          </Form.Item>
          <Form.Item name="type" label="交易类型">
            <Select placeholder="请选择交易类型" style={{ width: 150 }} allowClear>
              <Option value="payment">支付</Option>
              <Option value="refund">退款</Option>
              <Option value="recharge">充值</Option>
              <Option value="withdraw">提现</Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="交易状态">
            <Select placeholder="请选择交易状态" style={{ width: 150 }} allowClear>
              <Option value="success">成功</Option>
              <Option value="pending">处理中</Option>
              <Option value="failed">失败</Option>
            </Select>
          </Form.Item>
          <Form.Item name="dateRange" label="交易时间">
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              placeholder={['开始时间', '结束时间']}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
          columns={columns}
          dataSource={transactions}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 1300 }}
        />

        <Modal
          title="交易详情"
          visible={detailVisible}
          onCancel={() => setDetailVisible(false)}
          footer={[
            <Button key="close" onClick={() => setDetailVisible(false)}>
              关闭
            </Button>,
          ]}
          width={800}
        >
          {currentTransaction && (
            <Descriptions bordered column={2}>
              <Descriptions.Item label="交易单号">{currentTransaction.transactionNo}</Descriptions.Item>
              <Descriptions.Item label="订单号">{currentTransaction.orderNo}</Descriptions.Item>
              <Descriptions.Item label="用户名">{currentTransaction.username}</Descriptions.Item>
              <Descriptions.Item label="交易金额">¥{currentTransaction.amount.toFixed(2)}</Descriptions.Item>
              <Descriptions.Item label="支付渠道">{currentTransaction.channelName}</Descriptions.Item>
              <Descriptions.Item label="交易类型">
                {{
                  'payment': '支付',
                  'refund': '退款',
                  'recharge': '充值',
                  'withdraw': '提现',
                }[currentTransaction.type] || currentTransaction.type}
              </Descriptions.Item>
              <Descriptions.Item label="交易状态">
                <Tag color={
                  currentTransaction.status === 'success' ? 'green' :
                  currentTransaction.status === 'pending' ? 'gold' :
                  currentTransaction.status === 'failed' ? 'red' : 'default'
                }>
                  {{
                    'success': '成功',
                    'pending': '处理中',
                    'failed': '失败',
                  }[currentTransaction.status] || currentTransaction.status}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="交易时间">{currentTransaction.createdAt}</Descriptions.Item>
              <Descriptions.Item label="完成时间" span={2}>
                {currentTransaction.finishedAt || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="交易描述" span={2}>
                {currentTransaction.description || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="第三方交易号" span={2}>
                {currentTransaction.thirdPartyNo || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="备注" span={2}>
                {currentTransaction.remark || '-'}
              </Descriptions.Item>
            </Descriptions>
          )}
        </Modal>
      </Card>
    </PageContainer>
  );
};

export default TransactionList;